package com.idea.dsl.validator;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.idea.dsl.model.DslResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * JSON DSL验证器
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class JsonDslValidator implements DslValidator {
    
    private final ObjectMapper objectMapper;
    
    @Override
    public DslResponse.ValidationResult validate(String dslContent, String dslType) {
        List<String> errors = new ArrayList<>();
        List<String> warnings = new ArrayList<>();
        boolean syntaxValid = true;
        boolean semanticValid = true;
        
        try {
            // 语法验证
            objectMapper.readTree(dslContent);
            log.debug("JSON语法验证通过");
            
        } catch (Exception e) {
            syntaxValid = false;
            errors.add("JSON语法错误: " + e.getMessage());
            log.warn("JSON语法验证失败: {}", e.getMessage());
        }
        
        // 语义验证（可以根据具体需求扩展）
        if (syntaxValid) {
            // 检查是否为空对象或数组
            if (dslContent.trim().equals("{}") || dslContent.trim().equals("[]")) {
                warnings.add("生成的JSON内容为空");
            }
        }
        
        boolean valid = syntaxValid && semanticValid && errors.isEmpty();
        
        return DslResponse.ValidationResult.builder()
                .valid(valid)
                .errors(errors)
                .warnings(warnings)
                .syntaxValid(syntaxValid)
                .semanticValid(semanticValid)
                .build();
    }
    
    @Override
    public String getSupportedDslType() {
        return "json";
    }
    
    @Override
    public boolean supports(String dslType) {
        return "json".equalsIgnoreCase(dslType);
    }
}
